<template>
	<skeleton :skeleton="{name:'history'}" :showSkeleton="showSkeleton">
		<block slot="content">
			<noData :showErrorTip="noData">
				<scroll-view slot='content' scroll-y class="msg-list" @scrolltolower="loadMore" @scrolltoupper="refresh">
					<msg-item v-for="(item,index) in msgData" :key="index" :msgItem="item" @itemClick='itemClick(item,index)'></msg-item>
				</scroll-view>
			</noData>
		</block>
	</skeleton>
</template>

<script>
	import {mapMutations} from 'vuex';
	import {isEmpty} from '@/utils/index';
	import msgItem from './msgItem';
	import msgService from '@/services/msg';
	const service = new msgService();
	export default {
		components: {
			msgItem
		},
		props: {
			curIndex: 0,
			selfIndex: 0,
			mailType: '',
		},

		data() {
			return {
				showSkeleton:true,
				noData:false,
				noMore:false,
				msgData: [],
				loaded: false,
				pageSize: 20,
				pageNum: 1,
				curItemIndex:-1
			}
		},
		watch: {
			curIndex(newVal) {
				if (newVal === this.selfIndex && !this.loaded) {
					this.loadData(1);
				}
			}
		},
		mounted() {
			uni.$on('readed',()=>{
				if(this.curItemIndex<0||isEmpty(this.msgData)||this.msgData.length<=this.curItemIndex){
					return;
				}
				this.msgData[this.curItemIndex].isRead = '1';
				this.curItemIndex =  -1;
			});
			if (this.curIndex === this.selfIndex && !this.loaded) {
				this.loadData(1);
			}
		},
		destroyed() {
			uni.$off('readed');
		},
		methods: {
			...mapMutations({
				setMsgContent: 'msgStore/setMsgContent',
			}),
			refresh() {
				this.loadData(1);
			},
			loadMore() {
				this.loadData(this.pageNum + 1);
			},
			itemClick(msgItem,index) {
				console.log('msgItem:',msgItem)
				msgItem.isRead = "1"
				this.curItemIndex = index;
				this.setMsgContent(msgItem.content);
				if(msgItem.pushType=='0'){//答疑消息
					uni.navigateTo({
						url:`/pages/exam/question/index?subjectId=${msgItem.typeId}&id=${msgItem.id}`
					})
				}else{
					uni.navigateTo({
						url:`/pages/message/inDetail?id=${msgItem.id}&isRead=${msgItem.isRead}`
					})
				}
			},
			loadData(pageNum) {
				this.loaded = true;
				const param = {
					pageSize: this.pageSize,
					pageNum: pageNum,
					mailType: this.mailType
				};
				service.getMailList(param).then(response => {
					if (response.success) {
						if (this.pageNum == 1) {
							this.msgData = response.result.list;
							this.noData = isEmpty(this.msgData);
							this.noMore = false;
						} else {
							this.msgData = [...this.msgData, ...response.result.list];
							this.noMore = !response.result.hasNextPage;
						}
						this.pageNum = pageNum;
					} else {
						uni.showToast({
							title: response.message,
							duration: 2000,
							icon: 'none'
						})
					}
				}).then(()=>{
					this.showSkeleton = false;
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.msg-list {
		padding: 0 22upx;
	}
</style>
